package com.sqx.modules.app.controller.app.apple;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;

public class AppStoreServerAPI {

    //沙箱环境
    private static final String APP_STORE_URL = "https://api.storekit-sandbox.itunes.apple.com/inApps/v1/transactions/{transactionId}";
    //生成环境
//    private static final String APP_STORE_URL = "https://api.storekit.itunes.apple.com/inApps/v1/transactions/{transactionId}";
    private static final String API_KEY = "your_api_key";
    private static final String TEAM_ID = "your_team_id";
    private static final String APPLE_ID = "your_apple_id";
    private static final String PASSWORD = "your_password";

    public static void main(String[] args) {
        String transactionId = "your_transaction_id";

        try {
            String response = getTransactionInfo(transactionId);
            System.out.println(response);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static String getTransactionInfo(String transactionId) throws Exception {
        String urlStr = APP_STORE_URL.replace("{transactionId}", transactionId);

        URL url = new URL(urlStr);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        conn.setRequestProperty("Content-Type", "application/json");
        conn.setRequestProperty("Authorization", "Basic " + getAuthorizationHeader());

        int responseCode = conn.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_OK) {
            BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String inputLine;
            StringBuilder response = new StringBuilder();

            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();

            return response.toString();
        } else {
            throw new RuntimeException("Failed : HTTP error code : " + responseCode);
        }
    }

    private static String getAuthorizationHeader() throws Exception {
        String credentials = APPLE_ID + ":" + PASSWORD;
        String encodedCredentials = java.util.Base64.getEncoder().encodeToString(credentials.getBytes(StandardCharsets.UTF_8));
        return encodedCredentials;
    }
}
